<template>
  <div class="w-full h-full flex justify-center items-center bg-blue-400">
    <div>
      <div class="text-4xl text-center p-5 font-bold text-white">登录</div>
      <div class="p-5 bg-white rounded-md">
        <v-sheet class="mx-auto" width="300">
          <v-form fast-fail @submit.prevent>
            <v-text-field v-model="username" label="用户名" />

            <v-text-field
              :append-inner-icon="visible ? mdiEye : mdiEyeOff"
              v-model="password"
              label="密码"
              :type="visible ? 'text' : 'password'"
              @click:append-inner="visible = !visible"
            />

            <span
              className="text-blue-500 cursor-pointer"
              @click="router.push('/register')"
              >暂无账号？这里注册</span
            >

            <v-btn
              class="mt-2 bg-blue-400"
              color="blue-darken-4"
              type="submit"
              block
              @click="toLogin"
              @keyup.enter="toLogin"
              >登录</v-btn
            >
          </v-form>
        </v-sheet>
      </div>
      <div class="text-xl text-center p-5 font-bold text-white">一块来聊天吧！</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, ref } from "vue";
import { login } from "@/api";
import { useUserInfoStore } from "@/store/userInfo";
import { useSocketInfoStore } from "@/store/webSocket";
import { SET_CACHE } from "@/utils/localCache";
import { useIndexDB } from "@/store/indexedDB";
import { mdiEye, mdiEyeOff } from "@mdi/js";
import { useRouter } from "vue-router";

const router = useRouter()

const username = ref<string>("");
const password = ref<string>("");

const visible = ref(false);
const interval = ref();

const userInfoStore = useUserInfoStore();
const wsInfoStore = useSocketInfoStore();
const DB = useIndexDB();
const toLogin = async () => {
  // 发起登录认证请求
  login({
    username: username.value,
    password: password.value,
  }).then(async (data) => {
    // 登录成功
    // 将 token 存储到本地
    SET_CACHE("token", data);
    // 获取用户信息
    userInfoStore.user.username = username.value;
    await userInfoStore.getUserInfo();

    // 打开数据库
    await DB.initDB();

    // 发起 websocket 连接
    let socket = await wsInfoStore.initWS();
    if (socket.readyState === socket.OPEN) {
      // 连接成功，跳转到聊天页
      router.push({ name: "chat" });
    } else {
      let flag = 5;
      // 每五秒查看是否连接上ws
      interval.value = setInterval(() => {
        flag--;
        socket.readyState === socket.OPEN && router.push("/");
        if (flag === 0) {
          // ws 连接失败
          clearInterval(interval.value);
        }
      }, 1000);
    }
  });
};

onBeforeUnmount(() => {
  clearInterval(interval.value);
});
</script>
